<?php

class model_firadio_php_sys_menu extends db {

    public function __construct() {
        //1：菜单分类表（用于编辑修改分类）
        $table = "firphp_menuclass menuclass";
        $db = db::getInstance();
        $this->firphp_menuclass = $db->table($table);
        unset($db, $table);
        //2：菜单项表（用于编辑修改菜单项）
        $db = db::getInstance();
        $this->firphp_menuitem = $db->table("firphp_menuitem");
        unset($db);
        //3：菜单树列表（用于GetTree的第二步取菜单项）
        $table = "firphp_menuitem menuitem";
        $table.=" LEFT JOIN firphp_menuclass menuclass ON menuclass.id=menuitem.menuclassid"; //连接【菜单分类】
        $db = db::getInstance();
        $this->firphp_itemwithclass = $db->table($table);
        unset($db, $table);
        //4：菜单分类列表详情（展示列表，用于GetTree的第一步取菜单分类）
        $table = "firphp_menuclass menuclass";
        $table.=" LEFT JOIN firphp_projmodule projmodule ON projmodule.id=menuclass.projmoduleid"; //连接【所属模块】
        $table.=" LEFT JOIN firphp_project project ON project.id=projmodule.projectid"; //连接【所属项目】
        $table.=" LEFT JOIN firphp_company company ON company.id=project.companyid"; //连接【所属公司】
        $db = db::getInstance();
        $this->firphp_menuclasswithappmodel = $db->table($table);
        unset($db, $table);
        //5：详细的菜单项列表，用于生成procedure代码时的菜单列表（控制器及行为方法）
        $table = "firphp_menuitem menuitem";
        $table.=" LEFT JOIN firphp_menuclass menuclass ON menuclass.id=menuitem.menuclassid"; //连接【菜单分类】
        $table.=" LEFT JOIN firphp_projmodule projmodule ON projmodule.id=menuclass.projmoduleid"; //连接【所属模块】
        $table.=" LEFT JOIN firphp_project project ON project.id=projmodule.projectid"; //连接【所属项目】
        $table.=" LEFT JOIN firphp_company company ON company.id=project.companyid"; //连接【所属公司】
        $db = db::getInstance();
        $this->firphp_itemwithclassext = $db->table($table);
        unset($db, $table);
        //$this->view = new view();
    }

    /*
     * 设置菜单项的CTRL执行过程
     */

    public function setCtrlProcedure($menuitemid, $proceduretext) {
        $this->firphp_menuitem->where("id='{0}'", array($menuitemid))->update(array('proceduretext' => $proceduretext));
    }

    public function getItems($type, $id = 0) {
        //model_firadio_php_sys_dwz::getPageInfo($this->firphp_itemwithclassext, $pageinfo);
        //获取菜单项列表，只要把禁用的过滤掉。隐藏的菜单也要加入列表
        //用于生成procedure代码时的菜单列表（控制器及行为方法）
        $field = $wheresql = "";
        $wherearr = array();
        if ($type == "makephpcode") {
            //要生成ctrl_menuitem.php时要用的列表
            $field = "menuitem.id,menuitem.menuclassid,menuitem.name,menuitem.proceduretext,menuclass.name classname,menuclass.parentdir,menuitem.tplfile,menuclass.projmoduleid";
            $field.= ",company.name companyname,project.name projectname,projmodule.name modulename"; //公司名称，项目名称，模块名称
            $wheresql = "menuitem.enable='1' AND menuclass.enable='1'";
            return($this->firphp_itemwithclassext->where($wheresql, $wherearr)->field($field)->select());
        } else if ($type == "admin") {
            //要列出给管理员编辑菜单的列表
            $field = "menuitem.id,menuitem.name,menuitem.title,menuclass.name classname,menuclass.parentdir,menuitem.enable,menuitem.visible,CONCAT(menuitem.enable,menuitem.visible) status";
            $wheresql = "1";
            $i = 0;
            $wherearr = array();
            foreach ($this->search as $key => $val) {
                //只有正确的搜索项才会被添加匹配
                if (preg_match("/^[a-z]{3,12}\.[a-z]{3,12}$/", $key) && $val !== '') {
                    $wheresql.= " AND {$key}='{" . $i . "}'";
                    $wherearr[] = $val;
                    $i++;
                }
            }
            $ret = $this->firphp_itemwithclassext->where($wheresql, $wherearr)->page($this->pageinfo)->field($field)->order($this->order, 'menuitem.id ASC')->select();
            return($ret);
        } else if ($type == 'byclassid') {
            return($this->firphp_menuitem->field('id,name,title')->where("menuclassid='{0}'", array($id))->select());
        }
    }

    /*
     * 获取菜单项信息（一行）
     */

    public function getItemById($id) {
        $row = $this->firphp_menuitem->where("id='{0}'", array($id))->getone();
        return($row);
    }

    /*
     * 获取分类列表（多行）
     */

    public function getClassList($projmoduleid) {
        $wherestr = "1"; //初始化条件字符串
        $wherearr = array(); //初始化条件数组
        if ($projmoduleid > 0) {
            $wherestr.=" AND projmodule.id='{0}'";
            $wherearr[] = $projmoduleid;
        }
        $row = $this->firphp_menuclasswithappmodel->field('menuclass.id,menuclass.name,menuclass.title,menuclass.parentdir,menuclass.enable,menuclass.visible,project.name projectname,company.name companyname,projmodule.name modulename')->where($wherestr, $wherearr)->select();
        return($row);
    }

    /*
     * 获取分类信息
     */

    public function getClassInfo($id) {
        $field = "menuclass.id,menuclass.name,menuclass.title,menuclass.parentdir,menuclass.enable,menuclass.visible,menuclass.defaitemid";
        $field.= ",company.name companyname,project.name projectname,projmodule.name modulename"; //公司名称，项目名称，模块名称
        $field.= ",menuclass.parentid,menuclass.projmoduleid"; //上级ID，所属模块ID
        $row = $this->firphp_menuclasswithappmodel->field($field)->where("menuclass.id='{0}'", array($id))->getone();
        return($row);
    }

    /*
     * 修改菜单分类配置（菜单分类名称，是否隐藏，是否启用）
     */

    public function setClassInfo($id, $post) {
        $row = array();
        $row['name'] = $post['name'];
        $row['title'] = $post['title'];
        $row['enable'] = $post['enable'];
        $row['visible'] = $post['visible'];
        $row['defaitemid'] = $post['defaitemid']; //设置默认菜单项
        $row = $this->firphp_menuclass->where("id='{0}'", array($id))->update($row);
        return($row);
    }

    /*
     * 修改菜单项配置（菜单项名称，是否隐藏，是否启用）
     */

    public function setItemInfo($id, $post) {
        $row = array();
        $row['name'] = $post['name'];
        $row['title'] = $post['title'];
        $row['enable'] = $post['enable'];
        $row['visible'] = $post['visible'];
        $row = $this->firphp_menuitem->where("id='{0}'", array($id))->update($row);
        return($row);
    }

    public function addItem($post) {
        $row = array();
        $row['menuclassid'] = $post['menuclassid'];
        $row['name'] = $post['name'];
        $row['title'] = $post['title'];
        $row['enable'] = $post['enable'];
        $row['visible'] = $post['visible'];
        $row = $this->firphp_menuitem->insert($row);
        return($row);
    }

    public function getTree() {
        //获取菜单树，要把禁用的与非可视菜单都过滤掉
        $rows = $this->firphp_menuclasswithappmodel->field('menuclass.id,menuclass.parentid,menuclass.title,menuclass.name,menuclass.parentdir,menuclass.level,menuclass.defaitemid')->where("menuclass.enable='1' AND menuclass.visible='1'", array())->orderby('menuclass.level ASC,menuclass.orderby ASC,menuclass.id ASC')->select();
        $menu = $menus = array();
        foreach ($rows as $key => $row) {
            $menu[$row['id']] = array();
            //$menu[$row['id']]['id'] = $row['id'];
            $menu[$row['id']]['type'] = 'folder';
            $menu[$row['id']]['title'] = $row['title'];
            $menu[$row['id']]['name'] = $row['name'];
            $menu[$row['id']]['defaitemid'] = $row['defaitemid'];
            if (1) {
                //从数据库中提取父名称
                $menu[$row['id']]['parentdir'] = $row['parentdir'];
            } else {
                //通过数组自动生成父名称
                if ($row['parentid'] == 0) {
                    //顶级标签没有父名称
                    $menu[$row['id']]['parentdir'] = '';
                } else {
                    if ($menu[$row['parentid']]['parentdir'] == '') {
                        //如果上级属于顶层菜单，他是没有父名称的，所以只要顶层菜单的name属性
                        $menu[$row['id']]['parentdir'] = $menu[$row['parentid']]['name'];
                    } else {
                        $menu[$row['id']]['parentdir'] = $menu[$row['parentid']]['parentdir'] . '_' . $menu[$row['parentid']]['name'];
                    }
                }
            }
            $menu[$row['id']]['sub'] = array();
            if ($row['level'] == 0) {
                $menus[] = &$menu[$row['id']]; //采用地址引用方式传递给$menus
            } else {
                $menu[$row['parentid']]['sub'][] = &$menu[$row['id']];
            }
        }
        $rows = $this->firphp_itemwithclass->field("menuitem.id,menuitem.name,menuitem.title,menuitem.menuclassid")->where("menuitem.enable='1' AND menuitem.visible='1' AND menuclass.enable='1' AND menuclass.visible='1'", array())->orderby('menuitem.id ASC')->select();
        foreach ($rows as $key => $row) {
            $menuc = &$menu[$row['menuclassid']];
            if (isset($menuc)) {
                //当菜单分类有设置默认菜单项的时候
                if ($menuc['defaitemid'] > 0) {
                    if ($menuc['defaitemid'] == $row['id']) {
                        $menuc['type'] = 'item';
                        unset($menuc['sub']);
                        $menuc['ctrl'] = ($menuc['parentdir'] == '') ? $menuc['name'] : $menuc['parentdir'] . '_' . $menuc['name'];
                        $menuc['action'] = $row['name'];
                    }
                    continue;
                }
                //给普通的菜单分类里加入菜单项
                $item = array();
                $item['id'] = $row['id'];
                $item['type'] = 'item';
                $item['ctrl'] = ($menuc['parentdir'] == '') ? $menuc['name'] : $menuc['parentdir'] . '_' . $menuc['name'];
                $item['action'] = $row['name'];
                $item['title'] = $row['title'];
                $menu[$row['menuclassid']]['sub'][] = $item;
            }
        }
        return($menus);
    }

    public function makephpclass($classname, $contents, $extends = '') {
        $data = '<?php' . "\r\n\r\n";
        $data.= 'class ' . $classname;
        if ($extends)
            $data.= ' extends ' . $extends;
        $data.= ' {' . "\r\n\r\n";
        $data.=$contents;
        $data.= '}';
        if (0) {
            $data.= "\r\n" . "\r\n" . '?>';
        }
        return($data);
    }

    public function makectrl($items) {
        //要生成ctrl_menuitem.php
        $tab = str_repeat(" ", 4); //缩进标志
        $model_procedure = new model_firadio_php_sys_procedure();
        $model_tablelist = new model_firadio_php_sys_tablelist();
        $classnamearr = $classdata = array();
        foreach ($items as $item) {
            $appname = $item['companyname'] . '_' . $item['projectname']; //
            $menuclassname = $item['parentdir'] . '_' . $item['classname']; //菜单目录名称
            $classname = 'ctrl_' . $appname . '_' . $item['modulename'] . '_' . $menuclassname;
            if (!isset($classdata[$classname])) {
                $classnamearr[] = array('classname' => $classname, 'modulename' => $item['modulename'], 'menuclassname' => $menuclassname, 'appname' => $appname);
                $classdata[$classname] = '';
            }
            echo '开始处理，菜单ID=' . $item['id'] . '<br>';
            $str = 'public function action_' . $item['name'] . '() {';
            $classdata[$classname] .= str_repeat($tab, 1) . $str . "\r\n";
            /*
             * ====Start开始类方法内的过程========
             */
            echo "[{$classname}-{$item['name']}]";
            //下面是读取firphp_tablelist表来生成代码
            if ($item['name'] == 'list') {
                $model_procphp = new model_firadio_php_sys_procphp($tab, 2);
                $item['proceduretext'] = $model_tablelist->getProcTextByItemId($item['menuclassid']);
                $model_procphp->loadarray(json_decode($item['proceduretext'], true));
                $classdata[$classname] .= $model_procphp->getphpcode();
            }
            if ($item['name'] == 'info') {
                $model_procphp = new model_firadio_php_sys_procphp($tab, 2);
                $item['proceduretext'] = $model_tablelist->getProcTextByItemId_info($item['menuclassid']);
                $model_procphp->loadarray(json_decode($item['proceduretext'], true));
                $classdata[$classname] .= $model_procphp->getphpcode();
            }
            //下面是读取procedure表来回去过程代码
            if (1) {
                $model_procphp = new model_firadio_php_sys_procphp($tab, 2);
                $item['proceduretext'] = $model_procedure->getProcTextByItemId($item['id'], 0);
                $model_procphp->loadarray(json_decode($item['proceduretext'], true)); //载入代码（数组）
                $classdata[$classname] .= $model_procphp->getphpcode();
            }
            /*
             * ====End结束类方法内的过程=======
             */
            $classdata[$classname].=str_repeat($tab, 2) . 'return($this->getdata());' . "\r\n";
            $classdata[$classname] .= str_repeat($tab, 1) . '}' . "\r\n" . "\r\n";
            echo "<br>";
        }
        //开始写出php文件，在$classnamearr包含了所有要写出的类，赋值到$item
        //print_r($classnamearr);
        foreach ($classnamearr as $item) {
            $data = $this->makephpclass($item['classname'], $classdata[$item['classname']], 'ctrl_firadio_php_admin_common');
            $item['appname'] = str_replace('_', '-', $item['appname']);
            file_put_contents(app::$APP_BASE . __DS__ . $item['appname'] . __DS__ . 'ctrl' . __DS__ . $item['modulename'] . __DS__ . $item['menuclassname'] . '.php', $data);
        }
    }

    public function makeview($items, $viewname) {
        //要生成\view\html\view_menuitem.php
        $tab = str_repeat(" ", 4); //缩进标志
        $model_procedure = new model_firadio_php_sys_procedure();
        $classnamearr = $classdata = array();
        /*
          $data.=str_repeat($tab, 1) . 'var $dwz;' . "\r\n\r\n";
          $data.=str_repeat($tab, 1) . 'public function __construct($data) {' . "\r\n";
          $data.=str_repeat($tab, 2) . '$this->dwz = new model_firadio_php_sys_dwz($data[\'ret\']);' . "\r\n";
          $data.=str_repeat($tab, 2) . '$this->assigndata($data);' . "\r\n";
          $data.=str_repeat($tab, 1) . '}' . "\r\n\r\n";
         */
        foreach ($items as $item) {
            $appname = $item['companyname'] . '_' . $item['projectname']; //
            $menuclassname = $item['parentdir'] . '_' . $item['classname']; //菜单目录名称
            $classname = 'view_' . $appname . '_' . $viewname . '_' . $menuclassname;
            if (!isset($classdata[$classname])) {
                $classnamearr[] = array('classname' => $classname, 'menuclassname' => $menuclassname, 'appname' => $appname);
                $classdata[$classname] = '';
            }
            $str = 'public function action_' . $item['name'] . '() {';
            $classdata[$classname].=str_repeat($tab, 1) . $str . "\r\n";
            //====Start========
            $model_procphp = new model_firadio_php_sys_procphp($tab, 3);
            $item['proceduretext'] = $model_procedure->getProcTextByItemId($item['id'], 1);
            $model_procphp->loadarray(json_decode($item['proceduretext'], true));
            $classdata[$classname] .= $model_procphp->getphpcode();
            //====End=======
            $tplfile = ($item['tplfile'] > '') ? '\'' . $item['tplfile'] . '\'' : ''; //判断下是否有值，没有默认菜单名
            $classdata[$classname].=str_repeat($tab, 2) . '$this->display(' . $tplfile . ');' . "\r\n";
            $classdata[$classname].=str_repeat($tab, 1) . '}' . "\r\n" . "\r\n";
        }
        //the file can not read :D:/firadio/googlecode/firphpapps\firadio-php\view\dwz\sys_menu.php
        foreach ($classnamearr as $item) {
            $data = $this->makephpclass($item['classname'], $classdata[$item['classname']], 'view_firadio_php_dwz_common');
            $item['appname'] = str_replace('_', '-', $item['appname']);
            file_put_contents(app::$APP_BASE . __DS__ . $item['appname'] . __DS__ . 'view' . __DS__ . $viewname . __DS__ . $item['menuclassname'] . '.php', $data);
        }
    }

}